<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-11-16 16:12:56
 * @LastEditors: Sam
 * @LastEditTime: 2020-11-23 14:30:52
 */
namespace app\api\controller;
use think\facade\Reqeust;
use services\UtilService as util;
use app\admin\model\User;
use app\admin\model\UserToken;
use think\facade\Db;

class Login {

    /**
     * 登录
     * @return void
     * @author Sam
     * @date 2020-11-16
     */
    public function index(){
        $data = util::postMore(['code']);
        if(!$data['code']) show(0,'缺少code');
        $appid  = config('wechat.appId');
        $secret = config('wechat.appSecret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $data['code'] . "&grant_type=authorization_code";
        Db::startTrans();
        try {
            $res = json_decode(httpRequest($url),true);
            if(isset($res['errcode'])){
                exception($res['errmsg']);
            }
            if(!$user = User::getByOpenid($res['openid'])){
                $user = User::create([
                    'openid' => $res['openid'],
                    'unionid' => $res['unionid'] ??'',
                    'session_key' => $res['session_key'] 
                ]);
            }
            $token = UserToken::get_token($user->id);
            Db::commit();
            show(1,'success',['token'=>$token]);
        } catch (\Exception $e) {
            Db::rollback();
            show(0,$e->getMessage());
        }
    }
}